package admin

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"go-admin-auth/app/lib"
	"go-admin-auth/gin_helper"
)

type tokenHandler struct {
}

var (
	TokenHandler = new(tokenHandler)
)

type TokenParams struct {
	Token string `json:"token" form:"token"`
}

func (h *tokenHandler) CheckAdminToken(c *gin.Context) {
	params := new(TokenParams)
	if err := c.ShouldBind(&params); err != nil {
		gin_helper.JsonErr(c, err)
		return
	}

	token, err := lib.VerifyAdminToken(params.Token)
	if err != nil {
		gin_helper.JsonErr(c, fmt.Errorf("in handler, "+err.Error()))
		return
	}

	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		gin_helper.JsonErr(c, errors.New("handler admin-token, claims无效"))
	}

	gin_helper.JsonOk(c, claims)
}

func (h *tokenHandler) CheckInnerToken(c *gin.Context) {
	params := new(TokenParams)
	if err := c.ShouldBind(&params); err != nil {
		gin_helper.JsonErr(c, err)
		return
	}

	token, err := lib.VerifyInnerToken(params.Token)
	if err != nil {
		gin_helper.JsonErr(c, fmt.Errorf("in handler, "+err.Error()))
		return
	}

	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		gin_helper.JsonErr(c, errors.New("handler inner-token, claims无效"))
	}

	gin_helper.JsonOk(c, claims)
}
